//
//  SampuxEquipmentListViewController.m
//  Sampux
//
//  Created by rzm on 16/7/4.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SPEquipmentListViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SampuxFBackViewController.h"
#import "SampuxPCenterViewController.h"
#import "SampuxEquipmentListView.h"
#import "SampuxEquipDetailViewController.h"
#import "SampuxAddEquipmentViewController.h"
#import "SampuxListTableViewCell.h"
#import "SmapuxSettingUnitButton.h"
#import "SampuxToolBarButton.h"
#import "SPEquipmentInstallViewController.h"
#import "SampuxListModel.h"
#import "MJRefreshStateHeader.h"
#import "SPDeviceMessage.h"
#import "SPUserBaseMessageModel.h"
#import "SampuxGetListValue.h"
#import "SPGetDeviceDetailValue.h"
#import "SampuxGetCurrentTime.h"
#import "SampuxQRCodeViewController.h"

#define UserKEY @"UserKEY"

@interface SPEquipmentListViewController ()<SampuxEquipmentListSelectedRowDelegate>
{
    NSIndexPath *indexPath;
}
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) NSMutableArray *itemArr;
@property (nonatomic, strong) SampuxEquipmentListView *listView;
@property (nonatomic, strong) SampuxCustomNavController *nav;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) NSMutableArray *count;
@property (nonatomic, assign) BOOL needRefresh;
@property (nonatomic, strong) NSMutableArray *tempArr;
@property (nonatomic, strong) GBInterMaster_Bean_DeviceInfo13001 *device;
@property (nonatomic, strong) NSMutableArray *getStatusArr;
@property (nonatomic,assign) BOOL isConnectOrNot;
@property (nonatomic, strong) UIImageView *imagev;

@end

@implementation SPEquipmentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _getStatusArr = [NSMutableArray array];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestList:) name:NOTIFICATION_RESPONSE_GET_DEVICE_LIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"setParameterSuccess" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStatus:) name:NOTIFICATION_RESPONSE_DEVICE_STATUS_13001 object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNewStatus:) name:NOTIFICATION_PUSH_DEVICE_STATUS_13001 object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectFail) name:@"socketConnectFail" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:@"socketConnectSuccess" object:nil];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults objectForKey:@"image"] == nil) {
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        _imagev = [[UIImageView alloc]initWithFrame:delegate.window.bounds];
        _imagev.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageVTapClick)];
        [_imagev addGestureRecognizer:tap];
        [delegate.window addSubview:_imagev];
        _imagev.image = imageNamed(@"image");
        [userDefaults setObject:@"a" forKey:@"image"];
        [userDefaults synchronize];
    } else {
//        [userDefaults removeObjectForKey:@"image"];
    }

    [self createAddBarBtnItem];
    [self createListVeiw];
    [self createToolBar];
}

- (void)imageVTapClick
{
    [_imagev removeFromSuperview];
}

- (void)connectSuccess
{
    self.isConnectOrNot = YES;
}

- (void)connectFail
{
    self.isConnectOrNot = NO;
    [NSThread sleepForTimeInterval:3];
    [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络设置"];
}

- (void)createAddBarBtnItem
{
    _nav = (SampuxCustomNavController *)self.navigationController;
    UIButton *rightBtn = [UIButton createButton];
    [rightBtn setImage:imageNamed(@"add") forState:UIControlStateNormal];
    self.rightBtn = rightBtn;
    rightBtn.frame = CGRectMake(kScreenWidth - 10 - 40, 20, 40, 40);
    [rightBtn addTarget:self action:@selector(addBarBtnClick) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.hitTestEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -20);
    [_nav.img addSubview:self.rightBtn];
}

- (void)createListVeiw
{
    _listView = [[SampuxEquipmentListView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_listView];
    _listView.listDelegate = self;
}

- (void)createToolBar
{
    UIView *toolBarBackView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height  - 49 , self.view.width, 49.)];
    [_listView addSubview:toolBarBackView];
//    toolBarBackView.backgroundColor = THSystemClearColor;
    toolBarBackView.backgroundColor = THWhiteAlplaColor(0.1);

    self.itemArr = [NSMutableArray array];
    NSArray *_imageArr = @[@"pcenter",@"exit"];
    NSArray *titleArr = @[@"个人中心",@"安全退出"];
    for (int i = 0; i < 2; i ++) {
//        SampuxToolBarButton *btn = [[SampuxToolBarButton alloc]initWithFrame:CGRectMake(i * toolBar.width/3, 0, toolBar.width/3, toolBar.height)];
        SampuxToolBarButton *btn = [[SampuxToolBarButton alloc]initWithFrame:CGRectMake(i *((toolBarBackView.width - 1)/2 + 1), 0, (toolBarBackView.width- 1)/2, toolBarBackView.height)];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:THSystemWhiteColor forState:UIControlStateNormal];
        btn.titleLabel.font = THFont(12);
        [btn setImage:imageNamed(_imageArr[i]) forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i + 100;
//        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn];
        [toolBarBackView addSubview:btn];
    }
}

- (void)btnClick:(UIButton *)btn
{
    if (btn.tag == 100)
    {
        SampuxPCenterViewController *pCenterVC = [[SampuxPCenterViewController alloc]init];
        NSMutableArray *array = [NSMutableArray arrayWithArray:[self getUserIDic]];
        if (array.count) {
            [array enumerateObjectsUsingBlock:^(SPUserBaseMessageModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.isCurrentAccount) {
                     pCenterVC.teleStr = obj.phoneStr;
                    *stop = YES;
                }
            }];
        }
        [self.navigationController pushViewController:pCenterVC animated:YES];
    } else {
        [self exitApplication];
    }
}

- (void)saveUserMessageWithDic:(NSArray *)userArray
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *tokenObject = [NSKeyedArchiver archivedDataWithRootObject:userArray];
    [userDefaults setObject:tokenObject forKey:UserKEY];
    [userDefaults synchronize];
}

- (NSMutableArray *)getUserIDic
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:UserKEY];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return array;
}

- (void)exitApplication
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
}


- (void)addBarBtnClick
{
    SampuxQRCodeViewController *scanCodeVC = [[SampuxQRCodeViewController alloc]init];
    //    SPQRCodeViewController *scanCodeVC = [[SPQRCodeViewController alloc]init];
    [self.navigationController pushViewController:scanCodeVC animated:YES];
//
//    if ([self validateCamera] && [self canUseCamera]) {
//        SampuxQRCodeViewController *scanCodeVC = [[SampuxQRCodeViewController alloc]init];
//        //    SPQRCodeViewController *scanCodeVC = [[SPQRCodeViewController alloc]init];
//        [self.navigationController pushViewController:scanCodeVC animated:YES];
//
//        NSLog(@"haole");
//    } else {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有摄像头或摄像头不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertView show];
//    }
}

#pragma  mark SampuxEquipmentListSelectedRowDelegate

- (void)listTableViewSeletedRowIsONLine:(NSIndexPath *)index andDeviceModel:(SampuxListModel *)listModel
{
    indexPath = index;
    SampuxEquipDetailViewController *detailVC = [[SampuxEquipDetailViewController alloc]init];
    detailVC.detailModel = listModel;//用于传accout
    if (listModel.nameStr.length == 0) {
        detailVC.titleStr = listModel.accountStr;
    }else
    {
        detailVC.titleStr = listModel.nameStr;
    }
    [self.navigationController pushViewController:detailVC animated:YES];

//    if (self.getStatusArr.count == [SPDeviceMessage sharedManager].deviceMessageArr.count) {
//        detailVC.device = self.getStatusArr[index.row];
//        if (listModel.nameStr.length == 0) {
//            detailVC.titleStr = listModel.accountStr;
//        }else
//        {
//            detailVC.titleStr = listModel.nameStr;
//        }
//        [self.navigationController pushViewController:detailVC animated:YES];
//
//    }
}

- (void)listTableViewSeletedRowIsOffLine:(NSIndexPath *)index andDeviceModel:(SampuxListModel *)listModel
{
    indexPath = index;
    SPEquipmentInstallViewController *installVC = [[SPEquipmentInstallViewController alloc]init];
    installVC.model = listModel;
//    if (self.getStatusArr.count == [SPDeviceMessage sharedManager].deviceMessageArr.count) {
//        installVC.model = [SPGetDeviceDetailValue getDetailData:self.getStatusArr[index.row]];;
        [self.navigationController pushViewController:installVC animated:YES];
//    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    SampuxListTableViewCell *cell = [_listView.listTableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = THWhiteAlplaColor(0.1);
    cell.redView.backgroundColor = THSystemClearColor;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    _nav.button.hidden = NO;
    self.rightBtn.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    _nav = (SampuxCustomNavController *)self.navigationController;
    _nav.titleStr = @"我的设备";
    _nav.button.hidden = YES;
    self.rightBtn.hidden = NO;
//    _nav.img.image = imageNamed(@"nav");

//    if (self.needRefresh == YES) {
//        [_listView.listTableView.mj_header beginRefreshing];
//    }
    [_listView.listTableView.mj_header beginRefreshing];

}

- (void )requestList:(NSNotification* )notification{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestList == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    _tempArr = [NSMutableArray array];

    [SVProgressHUD dismiss];
//    [MBProgressHUD hideHUD];
    if(responseCode == 0x00){
        NSMutableArray* devices = (NSMutableArray*)[result objectForKey:@"devices"];
        if(devices.count > 0){
            for (GBInterMaster_Bean_DeviceInfo* device in devices) {
                if(device.deviceType == DEVICE_TYPE_AMPUX_GM8_13001){
                    GBInterMaster_Bean_DeviceInfo13001* bean = (GBInterMaster_Bean_DeviceInfo13001*)device;
                    [_tempArr addObject:bean];
                }
            }
        }
        [self obtainListData:_tempArr];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"获取列表失败"];

//        [MBProgressHUD showError:@"获取列表失败"];
    }
}

- (void)refreshData
{
    self.needRefresh = YES;
}

- (void)obtainListData:(NSMutableArray *)dataArr
{
    NSMutableArray *tempModelArr = [NSMutableArray array];
    [self.listView.dataSourceArr removeAllObjects];
    if (dataArr.count > 0) {
        tempModelArr = [SampuxGetListValue getListData:dataArr];
        self.listView.dataSourceArr = tempModelArr;
        [SPDeviceMessage sharedManager].deviceMessageArr = tempModelArr;
    }else
    {
        self.listView.dataSourceArr = self.listView.dataSourceArr;
    }
    
    [_getStatusArr removeAllObjects];
    [[SPDeviceMessage sharedManager].deviceMessageArr enumerateObjectsUsingBlock:^(SampuxListModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [GBInterMaster_CommForDeivce requestDeviceStatus:0 withDeviceAccount:obj.accountStr];
    }];
}

- (void)getStatus:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
  
    if(responseCode == 0x00)
    {
        [_getStatusArr addObject:[result objectForKey:@"device"]];
    }else
    {
//        [MBProgressHUD showError:@"获取最新状态失败"];
    }
}

- (void)getNewStatus:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"getNewStatus == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00)
    {
//        CGFloat getNewDate = [SampuxGetCurrentTime getCurrentTimeDate];
        GBInterMaster_Bean_DeviceInfo13001 *device = [result objectForKey:@"device"];
        NSMutableArray *arr = [NSMutableArray array];
        [self.listView.dataSourceArr enumerateObjectsUsingBlock:^(SampuxListModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            {
                SampuxListModel *model = nil;
                if ([device.account isEqualToString:obj.accountStr])
                {
                    model = [SampuxGetListValue beanChangeToModel:device];
                    model.nameStr = obj.nameStr;
                }else
                {
                    model = obj;
                }
                [arr addObject:model];
            }
        }];
        self.listView.dataSourceArr = arr;
    }else
    {
//        [MBProgressHUD showError:@"获取最新推送状态失败"];
    }
}
/*
-(BOOL)canUseCamera {
    
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        NSLog(@"相机权限受限");
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在设备的设置-隐私-相机中允许访问相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return NO;
    }
    
    return YES;
    
}

-(BOOL)validateCamera {
    
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
    [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
*/
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
